package ex.datastream.watermark;

import ex.datastream.functions.sourceFunction.SourceFuncByEvent;
import ex.vo.Event;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

public class TumblingEventTimeWindow01 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<Event> stream= env.addSource(new SourceFuncByEvent());
        stream.print("stream");
        WatermarkStrategy<Event> strategy = WatermarkStrategy
                .<Event>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner((event, timestamp) -> event.timestamp);

        DataStream<Event> withTimestampsAndWatermarks =
                stream.assignTimestampsAndWatermarks(strategy);

        withTimestampsAndWatermarks.keyBy(x -> x.key)
                .window(TumblingEventTimeWindows.of(Time.minutes(1)))
                .reduce(new ReduceFunction<Event>() {
                    @Override
                    public Event reduce(Event event, Event t1) throws Exception {
                        System.out.printf("event:%s,t1:%s \n",event.toString(),t1.toString());
                        return event.key.equals(t1.key)? event: t1;
                    }
                }).print("reduce");

        env.execute();
    }


}
